<html lang="zh-CN"><head><meta charset="UTF-8"><style>.nodata  main {width:1000px;margin: auto;}</style></head><body class="nodata " style=""><div class="main_father clearfix d-flex justify-content-center " style="height:100%;"> <div class="container clearfix " id="mainBox"><main><div class="blog-content-box">
<div class="article-header-box">
<div class="article-header">
<div class="article-title-box">
<h1 class="title-article" id="articleContentId">(A卷,100分)- 单词倒序（Java & JS & Python）</h1>
</div>
</div>
</div>
<div id="blogHuaweiyunAdvert"></div>

        <div id="article_content" class="article_content clearfix">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/kdoc_html_views-1a98987dfd.css">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-044f2cf1dc.css">
                <div id="content_views" class="htmledit_views">
                    <h4 id="main-toc">题目描述</h4> 
<p>输入单行英文句子&#xff0c;里面包含英文字母&#xff0c;空格以及,.?三种标点符号&#xff0c;请将句子内每个单词进行倒序&#xff0c;并输出倒序后的语句。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%85%A5%E6%8F%8F%E8%BF%B0">输入描述</h4> 
<p>输入字符串S&#xff0c;S的长度 1 ≤ N ≤ 100</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%87%BA%E6%8F%8F%E8%BF%B0">输出描述</h4> 
<p>输出倒序后的字符串</p> 
<p></p> 
<h4>备注</h4> 
<p>标点符号左右的空格 ≥ 0&#xff0c;单词间空格&#xff1e;0</p> 
<p></p> 
<h4 id="%E7%94%A8%E4%BE%8B">用例</h4> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">yM eman si boB.</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">My name is Bob.</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;">无</td></tr></tbody></table> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">woh era uoy ? I ma enif.</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">how are you ? I am fine.</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;">无</td></tr></tbody></table> 
<h4 id="%E9%A2%98%E7%9B%AE%E8%A7%A3%E6%9E%90">题目解析</h4> 
<p>从用例可以看出&#xff0c;单词的倒序并不难&#xff0c;将字符串单词转为字符数组后&#xff0c;reverse一下就行了。但是单词中如果有标点符号的话&#xff0c;则标点符号的位置不能改变&#xff0c;比如enif. 倒序后为 fine. 其中 . 的位置在倒序前后是一样的。</p> 
<p></p> 
<p>我的解题思路如下&#xff0c;从左到右遍历每一个字符&#xff0c;如果字符是 , . ? 或者空格&#xff0c;则看成一个分界符&#xff0c;将分界符之间的单词片段进行倒序。</p> 
<p></p> 
<h4 id="%E7%AE%97%E6%B3%95%E6%BA%90%E7%A0%81">JavaScript算法源码</h4> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

rl.on(&#34;line&#34;, (line) &#61;&gt; {
  console.log(getResult(line));
});

function getResult(str) {
  const reg &#61; /[\,\.\?\s]/;
  const idxs &#61; [-1];

  for (let i &#61; 0; i &lt; str.length; i&#43;&#43;) {
    if (reg.test(str[i])) {
      idxs.push(i);
    }
  }

  idxs.push(str.length);

  const arr &#61; [...str];

  idxs.reduce((p, c) &#61;&gt; {
    let l &#61; p &#43; 1;
    let r &#61; c - 1;

    while (l &lt; r) {
      let tmp &#61; arr[l];
      arr[l] &#61; arr[r];
      arr[r] &#61; tmp;
      l&#43;&#43;;
      r--;
    }

    return c;
  });

  return arr.join(&#34;&#34;);
}
</code></pre> 
<p></p> 
<p>更精简的解法&#xff0c;可以利用String.prototype.repalce的正则匹配出输入字符串中各个英文子串&#xff0c;将这些英文子串替换为倒序子串&#xff0c;关于repalce的正则匹配用法请看&#xff1a;</p> 
<p><a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/replace" rel="nofollow" title="String.prototype.replace() - JavaScript | MDN (mozilla.org)">String.prototype.replace() - JavaScript | MDN (mozilla.org)</a></p> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

rl.on(&#34;line&#34;, (line) &#61;&gt; {
  console.log(getResult(line));
});

function getResult(str) {
  return str.replace(/[a-zA-Z]&#43;/g, (s) &#61;&gt; [...s].reverse().join(&#34;&#34;));
}
</code></pre> 
<p></p> 
<h4>Java算法源码</h4> 
<pre><code class="language-java">import java.util.ArrayList;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);

    String str &#61; sc.nextLine();
    System.out.println(getResult(str));
  }

  public static String getResult(String str) {
    ArrayList&lt;Integer&gt; idxs &#61; new ArrayList&lt;&gt;();

    idxs.add(-1);
    for (int i &#61; 0; i &lt; str.length(); i&#43;&#43;) {
      if (&#34;,.? &#34;.indexOf(str.charAt(i)) !&#61; -1) {
        idxs.add(i);
      }
    }
    idxs.add(str.length());

    char[] chars &#61; str.toCharArray();

    for (int i &#61; 0; i &lt; idxs.size() - 1; i&#43;&#43;) {
      int l &#61; idxs.get(i) &#43; 1;
      int r &#61; idxs.get(i &#43; 1) - 1;

      while (l &lt; r) {
        char tmp &#61; chars[l];
        chars[l] &#61; chars[r];
        chars[r] &#61; tmp;
        l&#43;&#43;;
        r--;
      }
    }

    StringBuilder sb &#61; new StringBuilder();
    for (char c : chars) {
      sb.append(c);
    }
    return sb.toString();
  }
}
</code></pre> 
<p></p> 
<h4>Python算法源码</h4> 
<pre><code class="language-python">import re

s &#61; input()

p &#61; re.compile(r&#34;[\\,\\.\\?\s]&#34;)

idxs &#61; [-1]

for i in range(len(s)):
    if p.match(s[i]):
        idxs.append(i)

idxs.append(len(s))

arr &#61; [c for c in s]

for i in range(len(idxs) - 1):
    l &#61; idxs[i] &#43; 1
    r &#61; idxs[i &#43; 1] - 1

    while l &lt; r:
        arr[l], arr[r] &#61; arr[r], arr[l]
        l &#43;&#61; 1
        r -&#61; 1

print(&#34;&#34;.join(arr))
</code></pre> 
<p></p> 
<p> 更精简的&#xff0c;可以利用re.sub(pattern, repl, string, count&#61;0, flags&#61;0)</p> 
<p>其中repl可以是一个函数&#xff0c;该函数接收被pattern正则匹配结果re.Match类型的值作为入参matched&#xff0c;我们可以通过matched.group()获取出匹配的子串&#xff0c;并对它做反转处理&#xff0c;然后返回给re.sub进行替换</p> 
<pre><code class="language-python">import re

s &#61; input()


def rep(matched):
    tmp &#61; list(matched.group())
    tmp.reverse()
    return &#34;&#34;.join(tmp)


print(re.sub(r&#34;[a-zA-Z]&#43;&#34;, rep, s))
</code></pre> 
<p></p>
                </div>
        </div>
        <div id="treeSkill"></div>
        <div id="blogExtensionBox" style="width:400px;margin:auto;margin-top:12px" class="blog-extension-box"></div>
    <script>
  $(function() {
    setTimeout(function () {
      var mathcodeList = document.querySelectorAll('.htmledit_views img.mathcode');
      if (mathcodeList.length > 0) {
        for (let i = 0; i < mathcodeList.length; i++) {
          if (mathcodeList[i].naturalWidth === 0 || mathcodeList[i].naturalHeight === 0) {
            var alt = mathcodeList[i].alt;
            alt = '\\(' + alt + '\\)';
            var curSpan = $('<span class="img-codecogs"></span>');
            curSpan.text(alt);
            $(mathcodeList[i]).before(curSpan);
            $(mathcodeList[i]).remove();
          }
        }
        MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
      }
    }, 1000)
  });
</script>
</div></html>